#!/usr/bin/env python3
# coding: utf-8
# Copyright 2024 Huawei Technologies Co., Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
# ===========================================================================
import os
import platform
import glob
import json
from ansible.module_utils import common_utils
from ansible.module_utils.basic import AnsibleModule


class MisImageUninstaller:

    def __init__(self):
        self.module = AnsibleModule(
            argument_spec=dict(
                tags=dict(type="list", required=True),
                resources_dir=dict(type="str", required=True),
            )
        )
        self.run_tags = self.module.params["tags"]
        self.resources_dir = os.path.expanduser(self.module.params["resources_dir"])
        self.messages = [] 

    def _module_failed(self):
        """失败时返回日志信息"""
        return self.module.fail_json(msg="\n".join(self.messages), rc=1, changed=False)

    def _module_success(self):
        """成功时返回日志信息"""
        return self.module.exit_json(msg="Uninstall MIS container success.", rc=0, changed=True)

    def _check_docker_env(self):
        """检查Docker环境"""
        self.messages.append("[ASCEND] Checking Docker environment...")
        
        # 检查Docker是否安装
        docker_path = self.module.get_bin_path("docker", required=False)
        if not docker_path:
            self.messages.append("[ASCEND][ERROR] Docker not installed, please install docker first.")
            self._module_failed()
        self.messages.append("[ASCEND] Docker is installed at: {}".format(docker_path))
        
        return docker_path

    def _find_mis_pkg(self, pattern):
        try:
            pkgs, msgs = common_utils.find_files(os.path.join(self.resources_dir, "conf*"), pattern)
        except Exception as err:
            self.module.fail_json(msg='[ASCEND][ERROR] find mis package failed, error:{}'.format(err))
        self.messages.extend(msgs)
        if not pkgs:
            self.module.fail_json(msg='[ASCEND][ERROR] can not find mis package')
        return pkgs[0]

    def _get_config(self):
        config_path = self._find_mis_pkg("mis_image_config.json")
        with open(config_path, 'r') as f:
            self.config = json.load(f)

    def run(self):
        try:
            self._check_docker_env()
            self._get_config()
            for model_name, _ in self.config.items():
                common_utils.stop_and_rm_container(self.module, model_name)
        except Exception as e:
            self.messages.append(str(e))
            self._module_failed()
        self._module_success()


def main():
    MisImageUninstaller().run()


if __name__ == "__main__":
    main()